package org.deng.vertx.springboot.web.controller;

import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;
import org.deng.vertx.common.util.file.FileUtils;
import org.deng.vertx.springboot.pojo.ResData;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Files;

/**
 * @author 邓力宾
 * @date 2022/12/29 13:54
 * @desc
 */
@Slf4j
@Component
public class FileController extends BaseController{
    @Override
    public void configRouter(Router router) {
        //上传
        router.route("/file/upload").method(HttpMethod.POST).blockingHandler(this::upload);
        router.route("/file/down").method(HttpMethod.GET).blockingHandler(this::down);
    }

    /**
     * 下载文件
     * @param ctx
     */

    private void down(RoutingContext ctx) {
        File file = new File("D:\\upload\\《傲剑凌云》（校对版全本）作者：小刀锋利.txt");
        log.info("下载文件");
        try {
            ctx.response()
                    .putHeader("content-type", "application/octet-stream")
                    .putHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "utf-8"))
                    .sendFile(file.getAbsolutePath());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 文件上传
     * @param ctx
     */

    private void upload(RoutingContext ctx) {

        ctx.fileUploads().forEach(file->{
            log.info("文件上传,uploadedFileName:{}, fileName:{}, name:{}",file.uploadedFileName(), file.fileName(), file.name());
            try {
                FileUtils.copyFile(
                        Files.newInputStream(new File(file.uploadedFileName()).toPath()),
                        Files.newOutputStream(new File("D:/upload/"+file.fileName()).toPath()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        writeJSON(ctx, ResData.okData("成功"));
    }
}
